package com.legolas.demo.web.controller;

import com.legolas.demo.domain.Resource;
import com.legolas.demo.service.RoleService;
import com.legolas.demo.service.UserService;
import com.legolas.demo.domain.Role;
import com.legolas.demo.domain.User;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;


    //无权限
    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        String str = (String) SecurityUtils.getSubject().getSession().getAttribute("user_info");
        return "response userName " + str + " !";
    }


    //无权限
    @RequestMapping("/noAuthority")
    public String noAuthority() {
        return "/shiro/noAuthority";
    }

    //添加用户界面视图
    @RequestMapping("/addView")
    public String addView(Model model) {
        List<Role> roles = roleService.queryAllRole();
        model.addAttribute("roleList", roles);
        return "/shiro/user/addView";
    }

    //添加新用户
    @RequestMapping("/addUser")
    public String addUser(User user) {
        userService.add(user);
        //logger.info("插入的userId为->{}",user.getId());
        String roles = user.getRolesitems();
        if (StringUtils.isNotEmpty(roles)) {
            String[] strs = roles.split(",");
            for (String str : strs) {
                int roleId = Integer.parseInt(str);
                userService.addUserRole(user.getId(), roleId);
            }
        }
        return "redirect:/user/list";
    }

    //用户列表
    @RequestMapping("/list")
    public String list(Model model) {
        List<User> users = userService.queryAllUser();
        model.addAttribute("userList", users);
        return "/shiro/user/list";
    }

    //用户权限资源
    @RequestMapping("/res/{id}")
    public String res(Model model, @PathVariable int id) {
        //用户id查用户信息
        User user = userService.queryUserById(id);
        //用户id查用户资源信息
        List<Resource> resources = userService.queryResourceByUserId(id);
        model.addAttribute("resList", resources);
        model.addAttribute("user", user);
        return "/shiro/user/res";
    }

    //个人用户更新界面
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(Model model, @PathVariable int id) {
        User user = userService.queryUserById(id);
        List<Role> roles = roleService.queryAllRole();
        List<Role> my_roles = userService.queryRoleByUserId(id);
        List<Integer> rids = new ArrayList<Integer>();
        for (Role role : my_roles) {
            rids.add(role.getId());
        }
        model.addAttribute("user", user);
        model.addAttribute("roleList", roles);
        model.addAttribute("my_roles", rids);
        return "/shiro/user/update";
    }

    //更新用户请求
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(User user) {
        String roles = user.getRolesitems();
        userService.updateUser(user);
        if (StringUtils.isNotEmpty(roles)) {
            String[] strs = roles.split(",");
            //删除所有该用户的角色记录，重新填写角色记录
            userService.deleteUserRoleByUserId(user.getId());
            for (String str : strs) {
                int roleId = Integer.parseInt(str);
                userService.addUserRole(user.getId(), roleId);
            }
        }
        return "redirect:/user/list";
    }

    //删除用户
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String del(@PathVariable int id) {
        userService.deleteUser(id);
        userService.deleteUserRoleByUserId(id);
        return "redirect:/user/list";
    }

    //查看用户信息
    @RequestMapping("/info")
    public String info(Model model) {
        Subject subject = SecurityUtils.getSubject();
        String username = subject.getPrincipal().toString();
        User user = userService.queryUserByName(username);
        if (user == null) {
            return "/shiro/user/info";
        }
        int id = user.getId();
        List<Role> roles = userService.queryRoleByUserId(id);
        List<Resource> resources = userService.queryResourceByUserId(id);

        model.addAttribute("roleList", roles);
        model.addAttribute("resList", resources);
        return "/shiro/user/info";
    }
}
